package com.guang.mybatisplusgenerate.service.impl;

import com.guang.mybatisplusgenerate.service.BatchOperationApi;
import com.guang.mybatisplusgenerate.service.BatchOperationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

/**
 * @Description 批量操作服务接口实现
 * @Author lcy
 * @Date 2021/5/25 16:29
 */
@Service
@AllArgsConstructor
@Slf4j
public class BatchOperationServiceImpl implements BatchOperationService {

    /**
     * sqlSession工厂类
     */
    private final SqlSessionFactory sqlSessionFactory;

    @Override
    public boolean batchOperation(BatchOperationApi batchOperationApi){

        //获取批量sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);

        try {
            //执行批量操作
            batchOperationApi.operate(sqlSession);
            sqlSession.commit();
        } catch (Exception e) {
            log.error("批量操作失败");
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }
}
